package com.study.lxy.springcloud.uclient.filter;

import com.study.lxy.springcloud.common.entity.RequestLog;
import com.study.lxy.springcloud.common.utils.RequestLogUtil;
import com.study.lxy.springcloud.common.utils.servlet.MyHttpServletResponseWrapper;
import com.study.lxy.springcloud.uclient.dao.RequestLogDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebFilter(filterName = "saveLogFilter", urlPatterns = "/*")
/**
 * 对代码的侵入太大了，不使用filter记录log
 * 暂时无法解决ServletRequest 的InputStream只能读取一次的问题
 */
public class SaveLogFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(SaveLogFilter.class);

    @Autowired
    private RequestLogDao requestLogDao;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MyHttpServletResponseWrapper responseWrapper = new MyHttpServletResponseWrapper((HttpServletResponse) servletResponse);
        String requestData = RequestLogUtil.getRequestData((HttpServletRequest) servletRequest);
        filterChain.doFilter(servletRequest,responseWrapper);
        saveRequestLog(servletRequest,responseWrapper,requestData);
    }

    private void saveRequestLog(ServletRequest servletRequest,MyHttpServletResponseWrapper responseWrapper,String requestData){
        try {
            RequestLog log = RequestLogUtil.buildLog(servletRequest, responseWrapper,requestData);
            requestLogDao.saveRequestLog(log);
        } catch (Exception e){
            logger.error("save request log failed.",e);
        }
    }
}
